package rpc

import (
	"chat/rpc/pb"
	"context"
	"fmt"
	"log"
	"net"

	"google.golang.org/grpc"
)

var ClientConn *rpcClient

type rpcClient struct {
	cli []pb.IPCServiceClient
}

func Init(hosts []string) {
	run(hosts)
	rpc := &rpcClient{
		cli: make([]pb.IPCServiceClient, 0, 4),
	}
	for _, v := range hosts {
		conn, err := grpc.Dial(v, grpc.WithInsecure())
		if err != nil {
			fmt.Println(err)
			return
		}
		c := pb.NewIPCServiceClient(conn)
		rpc.cli = append(rpc.cli, c)
	}
	ClientConn = rpc
}

func run(host []string) {
	lis, err := net.Listen("tcp", host[0])
	if err != nil {
		return
	}
	s := grpc.NewServer()
	pb.RegisterIPCServiceServer(s, &server{})
	go s.Serve(lis)
}

func (c *rpcClient) Notify(data []byte) {
	for i := 0; i < len(c.cli); i++ {
		stream := c.cli[i]
		cli, err := stream.Notify(context.Background())
		if err != nil {
			log.Println(err)
			return
		}
		cli.Send(&pb.IPCFrame{Code: pb.IPC_chat, Data: data})
	}
}
